import os from 'os'
import express from 'express'
import { exec, execSync, execFile, spawn, fork } from 'child_process'
import path from 'path'
/* /system */

const router = express.Router() //路由模块
router.get('/info', (req, res) => {
  res.send({
    cpu: os.cpus(),
    networkInterfaces: os.networkInterfaces(),
    platform: os.platform(),
  })
})
router.get('/process', (req, res) => {
  console.log(req.query)
  res.send({
    arch: process.arch,
    cwd: process.cwd(),
    argv: process.argv,
    memoryUsage: process.memoryUsage,
    // exit:process.exit(),
    // kill:process.kill,
    env: process.env,
  })
})

router.get('/childprocess/exec', (req, res) => {
  console.log('childprocess', req.query)
  exec('node -v', (err, stdout, stderr) => {
    if (err) {
      return err
    }
    res.send({
      stdout: stdout.toString(),
    })
    console.log()
  })
})

router.get('/childprocess/execSync', (req, res) => {
  console.log('childprocess', req.query)
  execSync('start chrome http://www.baidu.com --incognito')
  res.send({
    stdout: 'ok',
  })
})

router.get('/childprocess/execFile', (req, res) => {
  console.log('childprocess', process.cwd())
  execFile(path.resolve(process.cwd(), './public/bat.cmd'), null, (err, stdout) => {
    console.log(stdout.toString())
    res.send({
      stdout: stdout.toString(),
    })
  })
})

router.get('/childprocess/spawn', (req, res) => {
  console.log('childprocess', process.cwd())
  let dataReceived = ''
  //                       命令      参数  options配置
  const { stdout } = spawn('netstat', ['-an'], {})
  //返回的数据用data事件接受
  stdout.on('data', steram => {
    console.log(steram.toString())
    dataReceived += `${steram.toString()}`
  })
  stdout.on('end', () => {
    console.log(dataReceived)
    res.send({
      stdout: dataReceived,
    })
  })
})

router.get('/childprocess/fork', (req, res) => {
  console.log('childprocess', process.cwd())
  const testProcess = fork('./public/aaa.js')
  testProcess.send('我是主进程')

  testProcess.on('message', data => {
    console.log('我是主进程接受消息111：', data)
  })
  testProcess.kill(); // 或者使用特定的信号，例如 worker.kill('SIGINT')
  testProcess.on('exit', (code, signal) => {
    console.log(`子进程退出，退出码：${code}，信号：${signal}`)
    // 在这里可以执行一些操作，比如清理资源、发送通知等
    res.send({
      stdout: `ok `,
    })
  })
})

export default router
